/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-08-16 15:55:00
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-08-21 11:56:33
 * @FilePath: /vue3-uniapp/src/service/hook/useAfterAuth.ts
 */
import { ReplaySubject } from 'rxjs';
import { onLoad } from '@dcloudio/uni-app';

import { useForkJoin } from '../rxjs/useForkJoin';

const afterAuthSubject = new ReplaySubject<boolean>(1);
const afterAuth$ = afterAuthSubject.pipe();

export const notifyAfterAtuh = (isAuth: boolean) => {
    afterAuthSubject.next(isAuth);
};

export const useAfterAuth = (fn: (option: AnyObject | undefined) => void) => {
    // 控制useAfterAuth在onLoad之后再触发
    const [excute1, excute2] = useForkJoin<AnyObject | undefined, undefined>(
        ([option]) => {
            fn(option);
        }
    );
    onLoad((option) => {
        excute1(option);
    });

    const afterAuthSubscription = afterAuth$.subscribe({
        next: (isAuth) => {
            if (isAuth) {
                excute2(undefined);
            }
        }
    });
    onBeforeUnmount(() => {
        afterAuthSubscription?.unsubscribe();
    });
};
